//
//  MusicViewController.m
//  CapriceMusic
//
//  Created by 蒋恩浩 on 16/1/16.
//  Copyright © 2016年 MYX. All rights reserved.
//

#import "MusicViewController.h"

@interface MusicViewController ()

// 音乐榜单列表
@property (nonatomic, strong) NSMutableArray *dataSource;
// 毛玻璃背景图
@property (nonatomic, strong) UIImageView *backImage;
// 歌手照片
@property (nonatomic, strong) UIImageView *singerPhoto;
// 图片旋转timer
@property (nonatomic, strong) NSTimer *picRotationTimer;
// 歌名 - 歌手
@property (nonatomic, strong) JEHLabel *detailLabel;

// 播放器对象
@property (nonatomic, strong) CapriceMusicPlayer *player;
// 当前播放的歌曲在数组的坐标
@property (nonatomic, assign) NSInteger currentMusicIndex;
// 进度条
@property (nonatomic, strong) UISlider *progressBar;
// 进度条timer
@property (nonatomic, strong) NSTimer *progressBarTimer;
// 播放暂停键
@property (nonatomic, strong) UIButton *playControlButton;
// 上一曲
@property (nonatomic, strong) UIButton *lastSongButton;
// 下一曲
@property (nonatomic, strong) UIButton *nextSongButton;
// 当前时间
@property (nonatomic, strong) JEHLabel *currentTimeLabel;
// 总时间
@property (nonatomic, strong) JEHLabel *totalTimeLabel;

@end

@implementation MusicViewController

static BOOL isPlay = YES;

static MusicViewController *singleMusicVC = nil;

#pragma mark - 创建单例播放器
+ (instancetype)shareSingleViewController {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        singleMusicVC = [[MusicViewController alloc] init];
    });
    return singleMusicVC;
}

#pragma mark - lifeCycle
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.tabBarController.tabBar.translucent = YES;
    self.tabBarController.tabBar.hidden = YES;
    // 关闭抽屉侧滑效果
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [tempAppDelegate.LeftSlideVC setPanEnabled:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.currentMusicIndex = 0;
    self.view.layer.masksToBounds = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self createView];
    [self getDataWithURL:kMusicGETURL];

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    self.tabBarController.tabBar.translucent = NO;
    self.tabBarController.tabBar.hidden = NO;
    [self.player pause];
    [self.picRotationTimer invalidate];
    [self.progressBarTimer invalidate];
}

#pragma mark - 创建视图
- (void)createView {
    
    // 背景图
    self.backImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - 64 - 120)];
    [self.view addSubview:self.backImage];
    // 毛玻璃效果
    UIVisualEffectView *visualEffect = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]];
    visualEffect.frame = CGRectMake(0, 0, self.view.width, self.view.height - 64);
    [self.view addSubview:visualEffect];
    // 播放器
    self.player = [CapriceMusicPlayer sharePlayer];
    // 添加播放完成的通知(自带通知)
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playFinishedAction) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
    // 歌手头像
    self.singerPhoto = [[UIImageView alloc] initWithFrame:CGRectMake(50, 50, self.view.width - 100, self.view.width - 100)];
    self.singerPhoto.layer.cornerRadius = (self.view.width - 100) / 2;
    // 头像旋转timer
    self.picRotationTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(picRotationTimerAction) userInfo:nil repeats:YES];
    [self.picRotationTimer setFireDate:[NSDate distantFuture]];
    [[NSRunLoop mainRunLoop] addTimer:self.picRotationTimer forMode:NSRunLoopCommonModes];
    // 图片适配
    self.singerPhoto.contentMode = UIViewContentModeScaleAspectFill;
    self.singerPhoto.clipsToBounds = YES;
    // 边框
    self.singerPhoto.layer.borderColor = [UIColor colorWithRed:34 / 255.0 green:34 / 255.0 blue:34 / 255.0 alpha:0.8].CGColor;
    self.singerPhoto.layer.borderWidth = 5;
    [self.view addSubview:self.singerPhoto];
    // 歌名 - 歌手
    self.detailLabel = [[JEHLabel alloc] initWithFrame:CGRectMake(10, self.view.height - 64 - 260, self.view.width - 20, 90) withFont:20 withTextColor:[UIColor colorWithRed:30 / 255.0 green:195 / 255.0 blue:153 / 255.0 alpha:1.0]];
    self.detailLabel.numberOfLines = 0;
    self.detailLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.detailLabel];
    // 进度条
    self.progressBar = [[UISlider alloc] initWithFrame:CGRectMake(80, self.view.height - 150 - 64, self.view.width - 160, 30)];
    self.progressBar.minimumValue = 0;
    self.progressBar.maximumValue = 1.0;
    [self.progressBar addTarget:self action:@selector(progressBarAction) forControlEvents:UIControlEventValueChanged];
    [self.progressBar setThumbImage:[UIImage imageNamed:@"HuaKuai"] forState:UIControlStateNormal];
    [self.view addSubview:self.progressBar];
    // 进度条点击手势
    UITapGestureRecognizer *sliderTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sliderTapAction:)];
    [self.progressBar addGestureRecognizer:sliderTap];
    // 进度条timer
    self.progressBarTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(progressBarTimerAction) userInfo:nil repeats:YES];
    [self.progressBarTimer setFireDate:[NSDate distantFuture]];
    [[NSRunLoop mainRunLoop] addTimer:self.progressBarTimer forMode:NSRunLoopCommonModes];
    // 当前时间
    self.currentTimeLabel = [[JEHLabel alloc] initWithFrame:CGRectMake(10, self.view.height - 150 - 64, 60, 30) withFont:14 withTextColor:[UIColor whiteColor]];
    self.currentTimeLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.currentTimeLabel];
    // 总时间
    self.totalTimeLabel = [[JEHLabel alloc] initWithFrame:CGRectMake(self.view.width - 70, self.view.height - 150 - 64, 60, 30) withFont:14 withTextColor:[UIColor whiteColor]];
    self.totalTimeLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.totalTimeLabel];
    // 播放暂停按钮
    self.playControlButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.playControlButton.frame = CGRectMake(self.view.width / 2 - 35, self.view.height - 100 - 64, 70, 70);
    [self.playControlButton setImage:[UIImage imageNamed:@"Pause"] forState:UIControlStateNormal];
    [self.playControlButton addTarget:self action:@selector(playControlButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.playControlButton];
    // 下一首
    self.nextSongButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.nextSongButton.frame = CGRectMake(self.view.width - 120, self.view.height - 90 - 64, 50, 50);
    [self.nextSongButton setImage:[UIImage imageNamed:@"Next"] forState:UIControlStateNormal];
    [self.nextSongButton addTarget:self action:@selector(nextSongButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.nextSongButton];
    // 上一首
    self.lastSongButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.lastSongButton.frame = CGRectMake(70, self.view.height - 90 - 64, 50, 50);
    [self.lastSongButton setImage:[UIImage imageNamed:@"Last"] forState:UIControlStateNormal];
    [self.lastSongButton addTarget:self action:@selector(lastSongButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.lastSongButton];
}

#pragma mark - 播放控制按钮
- (void)playControlButtonAction:(UIButton *)sender {
    
    if (CMTimeGetSeconds(self.player.currentItem.duration) > 0) {
        
        if (isPlay == NO) {
            
            [sender setImage:[UIImage imageNamed:@"Pause"] forState:UIControlStateNormal];
            [self.picRotationTimer setFireDate:[NSDate distantPast]];
            [self.player play];
            [self.progressBarTimer setFireDate:[NSDate distantPast]];
            isPlay = YES;
        } else {
            [sender setImage:[UIImage imageNamed:@"Play"] forState:UIControlStateNormal];
            [self.picRotationTimer setFireDate:[NSDate distantFuture]];
            [self.player pause];
            [self.progressBarTimer setFireDate:[NSDate distantFuture]];
            isPlay = NO;
        }
    }
}

#pragma mark - 下一首
- (void)nextSongButtonAction {
    
    [self playFinishedAction];
}

#pragma mark - 上一首
- (void)lastSongButtonAction {
    
    [self.player pause];
    if (self.dataSource.count > 0) {
        
        if (self.currentMusicIndex > 0) {
            
            self.currentMusicIndex -= 1;
            [self createMusicPlayer];
        } else {
            self.currentMusicIndex = self.dataSource.count - 1;
            [self createMusicPlayer];
        }
    }
}

#pragma mark - 头像旋转timerAction
- (void)picRotationTimerAction {
    
    self.singerPhoto.transform = CGAffineTransformRotate(self.singerPhoto.transform, 0.01);
}

#pragma mark - 进度条拖动事件
- (void)progressBarAction {
    
    if (CMTimeGetSeconds(self.player.currentItem.duration) > 0) {
        
        float playFromTime = self.progressBar.value * CMTimeGetSeconds(self.player.currentItem.duration);
        [self.player seekToTime:CMTimeMakeWithSeconds(playFromTime, 1.0)];
    }
}

#pragma mark - 进度条点击手势
- (void)sliderTapAction:(UITapGestureRecognizer *)sliderTap {
    
    if (CMTimeGetSeconds(self.player.currentItem.duration) > 0) {
        
        CGPoint point = [sliderTap locationInView:self.progressBar];
        self.progressBar.value = point.x / (self.view.width - 160);
        float playFromTime = self.progressBar.value * CMTimeGetSeconds(self.player.currentItem.duration);
        [self.player seekToTime:CMTimeMakeWithSeconds(playFromTime, 1.0)];
    }
}

#pragma mark - 进度条timerAction
- (void)progressBarTimerAction {
    
    self.progressBar.value = CMTimeGetSeconds(self.player.currentItem.currentTime) / CMTimeGetSeconds(self.player.currentItem.duration);
    NSInteger currentMinutes = self.progressBar.value * CMTimeGetSeconds(self.player.currentItem.duration) / 60;
    NSInteger currentSeconds = self.progressBar.value * CMTimeGetSeconds(self.player.currentItem.duration) - currentMinutes * 60;
    NSInteger totalMinutes = CMTimeGetSeconds(self.player.currentItem.duration) / 60;
    NSInteger totalSeconds = CMTimeGetSeconds(self.player.currentItem.duration) - totalMinutes * 60;
    if (CMTimeGetSeconds(self.player.currentItem.duration) > 0) {
        
        // 当前时间）
        self.currentTimeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld", currentMinutes, currentSeconds];
        // 总时间
        self.totalTimeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld", totalMinutes, totalSeconds];
        [self.picRotationTimer setFireDate:[NSDate distantPast]];
    }
}

#pragma mark - 播放完换歌通知方法
- (void)playFinishedAction {
    
    [self.player pause];
    if (self.dataSource.count > 0) {

        if (self.currentMusicIndex < self.dataSource.count - 1) {
            
            self.currentMusicIndex += 1;
            [self createMusicPlayer];
        } else {
            self.currentMusicIndex = 0;
            [self createMusicPlayer];
        }
    }
}

#pragma mark - 网络请求
- (void)getDataWithURL:(NSString *)url {
    
    self.dataSource = [NSMutableArray arrayWithCapacity:0];
    [JEHNetWorkTool getWithUrl:url parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
        
        if (result) {
            
            NSArray *array = result[@"songs"];
            for (NSDictionary *dic in array) {
                
                MusicModel *model = [[MusicModel alloc] initWithDictionary:dic];
                [self.dataSource addObject:model];
            }
        }
        NSLog(@"播放");
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self createMusicPlayer];
        });
    } fail:^(NSError *error) {
        
        NSLog(@"%@", error);
    }];
}

#pragma mark - 创建音乐播放器
- (void)createMusicPlayer {
    
    MusicModel *musicModel = self.dataSource[self.currentMusicIndex];
    // 导航标题
    self.navigationItem.title = [NSString stringWithFormat:@"%@", musicModel.title];
    // 背景图
    [self.backImage sd_setImageWithURL:[NSURL URLWithString:musicModel.singerImg]];
    // 歌手头像
    [self.singerPhoto sd_setImageWithURL:[NSURL URLWithString:musicModel.singerImg]];
    // 歌名 - 歌手
    self.detailLabel.text = [NSString stringWithFormat:@"%@\n\n%@", musicModel.title, musicModel.singer];
    // 播放器
    NSString *urlString = [musicModel.url stringByAppendingString:@"&ua=Iphone_Sst&version=4.2421&netType=1&toneFlag=1"];
    [self.player playWithURL:urlString];
    // 打开定时器
    [self.progressBarTimer setFireDate:[NSDate distantPast]];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
